package com.hanhanxiaochong.zhongxiangchuanmei.view.my.act;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.AddressItemBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.JsonBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.NewAddressPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.province.GetJsonDataUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.INewAddressView;

import org.json.JSONArray;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/5/9.
 * Desc   :
 */

public class NewAddressActivity extends BaseActivity<NewAddressPresenter> implements INewAddressView {

    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.text_address)
    TextView textAddress;
    @BindView(R.id.rlayout_address)
    RelativeLayout rlayoutAddress;
    @BindView(R.id.edit_address)
    EditText editAddress;
    @BindView(R.id.checkbox)
    CheckBox checkbox;

    //地址ID（地址ID为空,则为添加；否则为修改）
    private String addressId;
    private ParseDataHandler mHandler;
    //省市区
    private String province;
    private String city;
    private String district;
    //是否设置为默认地址,1:默认;0为非默认
    private String default_address = "0";

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int RESULT_NEW_ADDRESS = 0x0004;

    private String type;
    private AddressItemBean editBean;
    private String token;
    private String address_id;

    public static Intent createIntent(Context context, String type, Serializable bean) {
        Intent intent = new Intent(context, NewAddressActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("bean", bean);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_newaddress);
        token = SharedPreferencesUtil.getsInstances(this).getLoginInfo().getToken();
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        editBean = (AddressItemBean) intent.getSerializableExtra("bean");
    }

    @Override
    protected void initPresenter() {
        mPresenter = new NewAddressPresenter(this);
    }

    @Override
    protected void init() {
        setTopView();
        mHandler = new ParseDataHandler(this);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        if (editBean != null) {
            editName.setText(editBean.getShop_name());
            editPhone.setText(editBean.getPhone());
            province = editBean.getProvince();
            city = editBean.getCity();
            district = editBean.getArea();
            default_address = editBean.getDefaults();
            checkbox.setChecked(default_address.equals("1"));
            textAddress.setText(province + city + district);
            editAddress.setText(editBean.getAddress());
            address_id = editBean.getId();
        }
    }

    private void setTopView() {
        imgLeft.setImageResource(R.mipmap.icon_left);
        txtTitle.setText("编辑");
        txtRight.setText("完成");
    }

    @OnClick({R.id.ll_leftview, R.id.txt_right, R.id.rlayout_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_leftview:
                finish();
                break;
            case R.id.txt_right:
                String name = editName.getText().toString().trim();
                if (name.equals("")) {
                    ToastUtils.showToast("姓名不能为空");
                    return;
                }
                String phone = editPhone.getText().toString().trim();
                if (phone.equals("")) {
                    ToastUtils.showToast("手机号码不能为空");
                    return;
                }
                String addressDetail = editAddress.getText().toString().trim();
                if (addressDetail.equals("") && province == null) {
                    ToastUtils.showToast("地址不能为空");
                    return;
                }
                default_address = checkbox.isChecked() ? "1" : "0";
                if (type.equals("new")) {
                    mPresenter.addNewAddress(token, name, phone, province, city, district, addressDetail, default_address);
                } else if (type.equals("edit"))
                    mPresenter.editAddress(token, address_id, name, phone, province, city, district, addressDetail, default_address);
                break;
            case R.id.rlayout_address:
                ShowPickerView();
                break;
        }
    }

    @Override
    public void addNewAddressSuccess() {
        ToastUtils.showToast("添加收货地址成功");
        setResult(RESULT_NEW_ADDRESS, new Intent("address"));
        finish();
    }

    @Override
    public void editAddressSuccess() {
        ToastUtils.showToast("编辑收货地址成功");
        setResult(RESULT_NEW_ADDRESS, new Intent("address"));
        finish();
    }

    private static class ParseDataHandler extends Handler {
        private Thread thread;
        private final WeakReference<NewAddressActivity> mActivity;

        private ParseDataHandler(NewAddressActivity activity) {
            this.mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        // 写子线程中的操作,解析省市区数据
                        thread = new Thread(mActivity.get()::initJsonData);
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    Log.i(mActivity.getClass().getSimpleName(), "城市数据解析成功");
                    break;
                case MSG_LOAD_FAILED:
                    Log.i(mActivity.getClass().getSimpleName(), "城市数据解析失败");
                    break;

            }
        }
    }

    private void ShowPickerView() {// 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, (options1, options2, options3, v) -> {
            province = options1Items.get(options1).getName();
            city = options2Items.get(options1).get(options2);
            district = options3Items.get(options1).get(options2).get(options3);
            textAddress.setText(province + city + district);
        })
                .setLineSpacingMultiplier((float) 2.0)
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(16)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /*
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /*
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
//                    for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
//                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);
//                        City_AreaList.add(AreaName);//添加该城市所有地区数据
//                    }
                    //该城市对应地区所有数据
                    //添加该城市所有地区数据
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /*
             * 添加城市数据
             */
            options2Items.add(CityList);

            /*
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }
}
